<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
    <div id="app"></div>
</body>
<script>

    const validatorPlugin = (app, options) => {
        app.mixin({
            created () {
                // 令this指向vue实例化对象
                console.log(this.$options);
                for (const key in this.$options.rules) {
                    // 自定义的属性需要用$option获取
                    const item = this.$options.rules[key]
                    // watch侦听数据的变化
                    this.$watch(key, (value) => {
                        console.log(value, '更新后的数据');
                        const result = item.validator(value)
                        if (!result) {
                            console.log(item.message);
                        }
                    })
                }
            }
        })
    }
    let vm = {
        data () {
            return {
                name: 'alex',
                age: '18'
            }
        },
        // （这个是自定义属性）
        rules: {
            name: {
                // 校验规则
                validator: (name) => name.length >= 4,
                // 不满足规则返回的信息
                message: 'too short'
            },
            age: {
                validator: (age) => age > 18,
                message: 'too young'
            }

        }
    }
    const app = Vue.createApp(vm)
    app.use(validatorPlugin)
    let myVal = app.mount('#app')
</script>

</html>